"use strict";

var router = require("router"),
    TokenService = require("router").TokenService,
    mongo = require('./core/mongoservice'),
    ObjectId = require('mongodb').ObjectID,
    extensions = require('./core/extensions'),
    Q = require('q');

function UserReportService() {
    console.log("UserReportService constructor");
}
UserReportService.prototype = Object.create(TokenService.prototype);
UserReportService.prototype.constructor = UserReportService;

UserReportService.prototype.getFromToken = function (request, response, promise) {
    return promise.then(function (self) {
        self.identify(request, response);
        var userId = request.payload.user.id;
        return self.mongoGetByUserId(userId).then(function (report) {
            return response.send({ request: request, content: report });
        });
    });
};

/*-------------------------------------------------------*/
/*mongo daf*/

UserReportService.prototype.mongoGetByUserId = function (userId) {
    if (!alertId) throw new Error("userId is not defined.");
    var self = this;

    return mongo.findOne('users.reports', { "user.id": new ObjectId(userId) }).then(function (item) {
        item.reports = self.generateUserReports(item.reports); //replace reports
        return item;
    });
};

UserReportService.prototype.mongoInsert = function (user) {
    var self = this;

    var doc = { 
        user: { id: user._id},
        reports: []
    }

    return mongo.insert('users.reports', doc).then(function (docs) {
        return docs[0];
    }).then(function (doc) {
        return self.mongoUpdate(user);
    });
};

UserReportService.prototype.mongoPullCurrentReport = function (userId) {
    var self = this;

    var today = new Date();
    today.setHours(0, 0, 0, 0);
    var rp = { date: today };
    
    var report = {
        date: today,
        users: {
            near: [],
            subscriptions: []
        },
        shops: {
            near: [],
            subscriptions: []
        }
    };

    return mongo.update('users.reports', { "user.id": new ObjectId(userId) }, { $pull: { "reports": rp} }, {multi: true}).then(function () {
        return report;
    });
};

UserReportService.prototype.mongoPushCurrentReport = function (userId, report) {
    return mongo.update('users.reports', { "user.id": userId }, { $push: { "reports": report} });
}

UserReportService.prototype.mongoUpdate = function (user) {
    var self = this;
    return self.mongoPullCurrentReport(user._id).then(function (report) {

        report.users = user.users;
        report.shops = user.shops;

        return self.mongoPushCurrentReport(user._id, report);
    });
}

/*-------------------------------------------------------*/
/*common*/
UserReportService.prototype.generateUserReport = function (report) {
    if (!report) throw new Error("report is not defined.");

    var usersNearTotal = report.users.near.length;
    var usersNearRead = report.users.near.filter(function (element) {
        return element.read != undefined;
    }).length;

    var usersSubscriptionsTotal = report.users.subscriptions.length;
    var usersSubscriptionsRead = report.users.subscriptions.filter(function (element) {
        return element.read != undefined;
    }).length;

    return {
        date: report.date,
        users: {
            near: {
                total: usersNearTotal,
                read: usersNearRead,
                unread: usersNearTotal - usersNearRead
            },
            subscriptions: {
                total: usersSubscriptionsTotal,
                read: usersSubscriptionsRead,
                unread: usersSubscriptionsTotal - usersSubscriptionsRead
            }
        }
    };
};

UserReportService.prototype.generateUserReports = function (reports) {
    if (!reports) throw new Error("reports is not defined.");
    var self = this;

    var userReports = [];
    reports.forEach(function (report) {
        userReports.push(self.generateUserReport(report));
    });
    return userReports;
};

exports = module.exports = new UserReportService();